﻿/******************************************************************
 *Company: http://www.xiaomutech.com/
 *fileName : animationwidget.cpp --- AnimationWidget
 *Auth       : yhni (QQ:393320854)
 *Create    : 2022/2/12
 *Description   :
 *Histroy:
 *<Auth>    <Date>        <Ver>        <Content>
 *         2022/2/12
 *******************************************************************/
#include "animationwidget.h"

#include <QPainter>
#include <QDebug>

AnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent)
{
    m_direction = None;

    m_animation = new QPropertyAnimation(this, "imgpos");
    m_animation->setDuration(2000);
    m_animation->setEasingCurve(QEasingCurve::OutQuart);
    connect(m_animation, SIGNAL(finished()), this, SLOT(hide()));

    m_movie = new QMovie(this);
    connect(m_movie, SIGNAL(finished()), this, SLOT(hide()));
    connect(m_movie, SIGNAL(frameChanged(int)), this, SLOT(frameChanged(int)));
}

AnimationWidget::~AnimationWidget()
{

}

void AnimationWidget::setSource(const QString &_img, Direction _direction)
{
    this->show();
     m_direction = _direction;
    if (_img.endsWith("gif")) {
        m_movie->setFileName(_img);
        m_movie->stop();
        m_movie->start();
        return;
    }

    m_pixmap = QPixmap(_img);
    if (LeftToRight == _direction || RightToLeft == _direction) {
        int nY = (this->height() - m_pixmap.height()) / 2;
        m_animation->setStartValue(QPoint(LeftToRight == _direction ? -m_pixmap.width() : this->width(), nY));
        m_animation->setEndValue(QPoint(LeftToRight == _direction ? this->width() : -m_pixmap.width(), nY));
    }
    else if (BottomToTop == _direction || TopToBottom == _direction) {
        int nX = (this->width() - m_pixmap.width()) / 2;
        m_animation->setStartValue(QPoint(nX, BottomToTop == _direction ? this->height() : -m_pixmap.height()));
        m_animation->setEndValue(QPoint(nX, BottomToTop == _direction ? -m_pixmap.height() : this->height()));
    }

    if (None != _direction) m_animation->start();
}

QPoint AnimationWidget::imgPos() const
{
    return m_imgPos;
}

void AnimationWidget::setPoint(const QPoint &_pos)
{
    m_imgPos = _pos;
    this->update();
}

void AnimationWidget::frameChanged(int index)
{
    m_pixmap = m_movie->currentPixmap();
    m_imgPos = QPoint((this->width() - m_pixmap.width()) / 2, (this->height() - m_pixmap.height()) / 2);
    if ((index + 1) >= m_movie->frameCount()) {
        m_movie->stop();
        this->hide();
    }
    this->update();
}

void AnimationWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::SmoothPixmapTransform);
    painter.drawPixmap(m_imgPos, m_pixmap);
}
